import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_driver/FindGoods/AssignDrivers.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';
import '../l10n/messages.dart';

class VehicleAllocation extends StatefulWidget {
  const VehicleAllocation({super.key, required this.category});
  final int category;
  @override
  State<VehicleAllocation> createState() => _VehicleAllocationState();
}

class _VehicleAllocationState extends State<VehicleAllocation> {
  int pageNum=1;
  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  @override
  void initState() {
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });
    getFleetMessage();
    super.initState();
  }
  int selectedIndex = -1;
  List dataList=[];
  Future<void> getFleetMessage() async {
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/driver/fleet/user/vehiclePage",
      {'current':pageNum,"size":20,"captainId":"1781255212293775361"},
          (responseData)  {
        setState(() {
          if(pageNum==1){
            dataList=responseData['data']['records'];
          }else{
            dataList.addAll(responseData['data']['records']);
          }

        });

      },
    );

  }

  Future<void> getCarsAction(String searchKey) async {
    String?  drvId= await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      'api/auth/driver/fleet/user/vehiclePage',
      {
        "captainId": drvId,
        "pageSize": 20,
        "pageNum": 1,
        "searchKey": searchKey
      },
          (responseData) {
        setState(() {
          dataList=responseData['data']['records'];
        });

      },
    );
  }
  Future _onRefresh() async {

      pageNum=1;
      getFleetMessage();

  }
  Future<void> _loadMoreData() async {

      if (dataList.length > 20*pageNum-1 ){
        pageNum=pageNum+1;
        getFleetMessage();
      }



  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("车辆分配",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: Column(
        children: [
          Expanded(child: ListView(
            children: [
              Container(
                child: BrnSearchText(
                  focusNode: focusNode,
                  controller: textController,
                  searchController: scontroller..isActionShow = false,
                  outSideColor:MyColors.backgreyColor,
                  innerColor:Colors.white,
                  borderRadius:BorderRadius.all(const Radius.circular(10.0)),
                  hintText:"输入车牌号码",
                  onTextClear: () {
                    debugPrint('sss');
                    return false;
                  },
                  autoFocus: false,
                  onActionTap: () {
                    scontroller.isClearShow = false;
                    scontroller.isActionShow = false;
                    focusNode.unfocus();
                  },
                  onTextCommit: (text) {

                  },
                  onTextChange: (text) {
                    if(text!="") {
                      getCarsAction(text);
                    }else{
                      getFleetMessage();
                    }
                  },
                ),
              ),
              Container(
                padding: EdgeInsets.only(left: 27.w),
                child:  Text("可分配车辆",style: TextStyle(color: Colors.black),),
              ),
              EasyRefresh(
                  header:
                  ClassicHeader(
                    dragText: '下拉刷新',
                    armedText: '准备释放',
                    readyText: '加载中...',
                    processingText: '加载中...',
                    processedText: '刷新成功',
                    noMoreText: '暂无更多',
                    failedText: '刷新失败',
                    messageText: '刷新时间 %T',
                  ),

                  footer: ClassicFooter(
                    dragText: '加载更多',
                    armedText: '准备释放',
                    readyText: '加载中...',
                    processingText: '加载中...',
                    processedText: '加载成功',
                    noMoreText: '暂无更多',
                    failedText: '加载失败',
                    messageText: '加载时间 %T',
                  ),
                  onRefresh: _onRefresh,
                  onLoad: dataList.length > 20*pageNum-1?_loadMoreData:null,
                  child:
              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w),
                height: screenSize.height-240.h,
                child: ListView.builder(
                shrinkWrap:false,
                    itemCount:dataList.length,
                    itemBuilder: (BuildContext context, int index) {
                  return GestureDetector(
                    child: Container(
                    margin: EdgeInsets.only(top: 8.h),
                    padding: EdgeInsets.only(left: 17.w,top: 6.h,right:10.w,bottom: 3.h ),
                    decoration: BoxDecoration(
                        color:Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child:Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(dataList[index]['vehicleNum'].toString(),style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                  SizedBox(height: 4.h,),
                                  Text(dataList[index]['vehicleLength'].toString()+"米/"+dataList[index]['vehicleModel'].toString(),style: TextStyle(color: Colors.black,fontSize: 12.sp),),
                                  Row(
                                    children: [

                                      Text("行驶证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                      (dataList[index]['vehicleDrivingLicenseStatus']==0||dataList[index]['vehicleDrivingLicenseStatus']==3)?

                                      Icon(Icons.
                                      error_outline,color: Colors.red,size: 12,)
                                          :dataList[index]['vehicleDrivingLicenseStatus']==1?

                                      Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                          :
                                      Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),

                                      SizedBox(width: 8.w,),
                                      Text("道路运输证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                      (dataList[index]['roadTransportCertificateStatus']==0||dataList[index]['roadTransportCertificateStatus']==3)?

                                      Icon(Icons.
                                      error_outline,color: Colors.red,size: 12,)
                                          :dataList[index]['roadTransportCertificateStatus']==1?
                                      Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                          :
                                      Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),



                                    ],
                                  ),
                                ],
                              ),
                              if(selectedIndex == index ) Icon(Icons.check_circle,color: MyColors.themeColor,size:24,),
                              if(selectedIndex != index ) Icon(Icons.radio_button_off,color: MyColors.hintColor,size:24,),
                            ],
                          ),
                          Divider(height: 8.h,color: MyColors.backgreyColor,),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      Container(
                                        width:20.w,
                                        height: 20.h,
                                        child:  dataList[index]['avatarPath']!=null&&dataList[index]['avatarPath']!=""?
                                        CircleAvatar(
                                          radius: 15,
                                          backgroundImage: NetworkImage(MyServiceUrl.imgHeader +dataList[index]['avatarPath']),
                                        )
                                            :  CircleAvatar(
                                          radius: 15,
                                          backgroundImage: AssetImage("lib/Images/login/默认头像.jpeg"),
                                        ),
                                      ),
                                      SizedBox(width: 4.w,),
                                      Text(dataList[index]['realName'].toString(),style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                    ],
                                  ),
                                  Row(
                                    children: [
                                      Text("身份认证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                      (dataList[index]['personalStatus']==0||dataList[index]['personalStatus']==3)?

                                      Icon(Icons.
                                      error_outline,color: Colors.red,size: 12,)
                                          :dataList[index]['personalStatus']==1?

                                      Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                          :
                                      Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),

                                      SizedBox(width: 8.w,),
                                      Text("驾驶证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                      (dataList[index]['driverLicenseStatus']==0||dataList[index]['driverLicenseStatusdriverLicenseStatus']==3)?

                                      Icon(Icons.
                                      error_outline,color: Colors.red,size: 12,)
                                          :dataList[index]['driverLicenseStatus']==1?

                                      Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                          :
                                      Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),

                                      SizedBox(width: 8.w,),
                                      Text("从业资格证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                      (dataList[index]['qualificationCertificateStatus']==0||dataList[index]['qualificationCertificateStatus']==3)?

                                      Icon(Icons.
                                      error_outline,color: Colors.red,size: 12,)
                                          :dataList[index]['qualificationCertificateStatus']==1?

                                      Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                          :
                                      Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),

                                    ],
                                  ),

                                ],
                              ),

                              GestureDetector(
                                child: Row(
                                  children: [
                                    Text("换人",style: TextStyle(color: MyColors.textColor,fontSize:14.sp ),),
                                    SizedBox(width: 4.w,),
                                    Icon(Icons.arrow_forward_ios,color: MyColors.authTipColor,size:16,),
                                  ],
                                ),
                                onTap: () async {
                                  final result=await Navigator.push( context, FadeRoute(page:AssignDrivers(dataMap: dataList[index],)));

                                  if(result!=null){
                                    setState(() {
                                      dataList[index]['driverId']=result['driverId'];
                                      dataList[index]['avatarPath']=result['avatarPath'];
                                      dataList[index]['realName']=result['realName'];
                                      dataList[index]['personalStatus']=result['personalStatus'];
                                      dataList[index]['driverLicenseStatus']=result['driverLicenseStatus'];
                                      dataList[index]['qualificationCertificateStatus']=result['qualificationCertificateStatus'];
                                    });
                                  }
                                },
                              ),
                            ],
                          )
                        ],
                      ),

                    ),

                    onTap: (){
                      setState(() {
                        selectedIndex = index;
                      });
                    },
                  );
                    }
                ),
              )),

            ],
          ),
          ),
          Container(
            padding: EdgeInsets.only(left: 15.w,right: 15.w,top: 10.h,bottom: 40.h),
            color: Colors.white,
            height: 85.h,
            width: screenSize.width,
            child: BrnSmallMainButton(
              title: '确认分配',
              textColor: Colors.white,
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              bgColor: MyColors.themeColor,
              radius: 30,
              width: screenSize.width-30.w,
              onTap: () {
                if(selectedIndex!=-1){
                  if(widget.category==1){
                    if(dataList[selectedIndex]['personalStatus']==2&&dataList[selectedIndex]['driverLicenseStatus']==2
                    &&dataList[selectedIndex]['vehicleDrivingLicenseStatus']==2&&dataList[selectedIndex]['roadTransportCertificateStatus']==2&&dataList[selectedIndex]['qualificationCertificateStatus']==2){
                      Navigator.pop(context,dataList[selectedIndex]);
                    }else{
                      BrnToast.show("分配企业货源需要五证齐全", context);
                    }
                  }else{
                    Navigator.pop(context,dataList[selectedIndex]);
                  }

                }else{
                  BrnToast.show("请选择分配的车辆", context);
                }

              },
            ),
          )
        ],
      ),
    );
  }
}
